import { apiLogin, apigiteeLogin } from '../api'
import { Form, Input, Button } from 'antd';
import Cookie from 'js-cookie'
import React, { useEffect } from 'react'
import { useLocation } from 'react-router-dom'


const Login = () => {

    const location = useLocation();

    // data: 数据框中输入的内容
    const onFinish = (data) => {
        apiLogin(data).then(res => {
            // 将token 保存到本地
            Cookie.set('token', res.token)

            // 跳转到首页
            window.location.href = '/'
        })
    }

    useEffect(() => {
        const { search } = location
        if (search) {
            const code = search.replace('?code=', '')

            apigiteeLogin({ code }).then(res => {
                // 将token 保存到本地
                Cookie.set('token', res.token)

                // 跳转到首页
                window.location.href = '/'
            })
        }
    })

    const giteeLogin = () => {
        // 跳转到第三方授权页面
        window.location.href = 'https://gitee.com/oauth/authorize?client_id=9a21414f8733acff996d060b3c9d19734029f56d8a1283b71b6a910394757288&redirect_uri=http://10.1.33.16:3000/login&response_type=code'

    }


    return <div>
        <Form
            name="basic"
            onFinish={onFinish} // 验证成功的回调函数
            autoComplete="off"
        >
            <Form.Item
                label="Username"
                name="username"
                rules={[
                    {
                        required: true,
                        message: 'Please input your username!',
                    },
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="Password"
                name="password"
                rules={[
                    {
                        required: true,
                        message: 'Please input your password!',
                    },
                ]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item
            >
                <Button block type="primary" htmlType="submit">
                    登录
                </Button>

                <Button block type="dashed" onClick={giteeLogin}>码云登录</Button>
            </Form.Item>
        </Form>
    </div>
}

export default Login